<template>
	<ls-page :hidden="true" :hideTopbar="true" :backgroundImage="backGround" :default-bg="false">
    </ls-page>
</template>

<!-- 登录流程：
 1.获取code，
 2.用code换取微信信息与用户信息
 3.如果用户未开卡未注册（也就是未开通会员），则需要跳转到第三方地址去提交表单开卡，然后提交完，返回我的页面，去注册，然后存储注册成功返回的用户信息，然后去获取门店信息，再存储起来，最后获取卡列表信息，存储默认第一张卡信息。
 4.如果用户已经开卡已注册，则存储注册成功返回的用户信息，然后去获取门店信息，再存储起来，最后获取卡列表信息，存储默认第一张卡信息，最好跳转到首页。
 -->
<script setup> 
	import { onLoad, onShow } from '@dcloudio/uni-app';
	import { HFiveLogin, HFiveRegister, GetBaseConfigInfoH5,HFiveAppObjProcess,HFiveMemberAppObjProcess } from '@/api/public.js'
	import { updateTableInfo } from "@/until/tools.js"
	import { clearStoreGoodsNum } from "@/until/orderUtils.js" 
	import setting  from "@/common/config.js";
	
	// 首先扫描二维码 或者 通过拼接访问路径https://jtmckj.cn/kbq/#/pages/index?brandCode=xxxxx&orgCode=xxxxxxxxx
	// 然后将获取brandCode orgCode存储起来
	// 非常规处理  
	const backGround = ref('')
	
	
	onLoad((options) => { 
		// 此处转发地址，方便做本地测试
		let toolBrd = options.brd || uni.getStorageSync('shopInfo')?.brandCode
		switch (toolBrd) {
			case '0003': // 群青
				backGround.value = 'https://oss.jtmckj.com/wmp/qnjg/account/i_firing_rabit3.jpg'
				break;
			case '0004': // 赤红
				backGround.value = 'https://oss.jtmckj.com/crimsonred/i_firing_back2.png'
				break;
			case '0005': // 空白区
				backGround.value = 'https://oss.jtmckj.com/wmp/kbq/i_back1.png'
				break;
			case '0006': // 踏歌行
				backGround.value = 'https://jtmc.oss-cn-hangzhou.aliyuncs.com/wmp/tgx/common/i_back.png'
				break;
			case '0007': // 在逃兔兔
				backGround.value = 'https://oss.jtmckj.com/h5-uniapp/zttt/i_back.jpg'
				break;
			case '0008': // 馨现场
				backGround.value = 'https://oss.jtmckj.com/wmp/xin/i_back.png'
				break;
			case '0011': // ams
				backGround.value = 'https://jtmc.oss-cn-hangzhou.aliyuncs.com/wmp/ams/i_back.jpg'
				break;
			case '0029': // 艾斯酒馆
				backGround.value = 'https://jtmc.oss-cn-hangzhou.aliyuncs.com/wmp/as/as-back1.png'
				break;
			default:
				break;
		}
		if(options.userCode){
			uni.setStorageSync('promotionUser', options.userCode)
		}
		if(options.comSharingCardNo){
			uni.setStorageSync('comSharingCardNo', options.comSharingCardNo)
		}
		
		if(options.localTest && options.code){ 
			// （假设有code）
			let shopInfo = {
				'brandCode':'0004', // 0005空白区0018   0003群众青年0015  0006踏歌行0019 0007在逃兔兔0020  0004赤红
				'orgCode':'0024'
			}
			uni.setStorageSync('shopInfo',shopInfo) 
			uni.navigateTo({
				url:'/pages/account/firing/enter?code=' + options.code   
			})
		}else if(options.gift){ 
			let shopInfo = {
				'brandCode':options.brandCode,
				'orgCode':options.orgCode
			}
			let userInfo =  JSON.parse(decodeURIComponent(options.referrerInfo))  
			uni.setStorageSync('token', userInfo.token)
			uni.setStorageSync('userInfo',userInfo) 
			uni.setStorageSync('shopInfo',shopInfo)
			uni.redirectTo({
				url:'/subpkg/view/gift/gift'   
			})
		}else if(options.activate_ticket){
			// 开卡后 去注册
			toRegister(options.activate_ticket)
		}else if(options.brd && options.org){
			console.log(options);
			// 此处正常线上流程（假设有code） 
			let shopInfo = {
				'brandCode':options.brd,
				'orgCode':options.org,
			}
			let tableInfo = {
				'code':options.code,
				'name':options.name,
			}
			uni.setStorageSync('scanInfo',options)  // 扫码信息
			uni.setStorageSync('toPath',options.link)  // 跳转地址
			uni.setStorageSync('shopInfo',shopInfo)  // 门店信息
			uni.setStorageSync('tableInfo',tableInfo) // 桌台信息
			uni.setStorageSync('LoginFlag',true) // 标记为第一次
			getWxUserInfoCode() 
		} else if(options.org == '0015' && !options.brd){
			options.brd = '0003'
			console.log(options);
			// 此处正常线上流程（假设有code） 
			let shopInfo = {
				'brandCode':options.brd,
				'orgCode':options.org,
			}
			let tableInfo = {
				'code':options.code,
				'name':options.name,
			}
			uni.setStorageSync('scanInfo',options)  // 扫码信息
			uni.setStorageSync('toPath',options.link)  // 跳转地址
			uni.setStorageSync('shopInfo',shopInfo)  // 门店信息
			uni.setStorageSync('tableInfo',tableInfo) // 桌台信息
			uni.setStorageSync('LoginFlag',true) // 标记为第一次
			getWxUserInfoCode() 
		}else if (uni.getStorageSync('shopInfo')?.brandCode && uni.getStorageSync('shopInfo')?.orgCode ){
			uni.removeStorageSync('LoginFlag') // 去除第一次标记
			getWxUserInfoCode() 
		} else{ 
			// uni.showToast({ title: '请确认二维码或者链接地址是否正确？', icon: 'none' })
		}
		
		getConfigUrl()
		// try{
		// 	let temp = link.split("activate_ticket=")[1];
		// 	activate_ticket = temp.split("&")[0]; 
		// 	console.log('activate_ticket：',activate_ticket)
		// 	uni.showToast({ title: '有activate_ticket方法2', icon: 'none' }) 
		// 	return 
		// }catch(e){
		// 	//TODO handle the exception
		// }  
		// https://jtmckj.cn/kbq/
		// ?card_id=pDCMP66uVV8FcDgFnLovujEKdzkc
		// &encrypt_code=TN%2FXy6aurFz8r7BauFz3iv7ZIjSPDSZGiuii1Wzixl0%3D&openid=oDCMP6ytbfkBhWXk5o5LUUcLtE48
		// &outer_str=0017
		// &activate_ticket=fDZv9eMQAFfrNr3XBoqhb60OzCeHzNF3OMl%2FaVrovyMbfpa6yabwl8uc0nsz0vi%2BO1nSiAOONjoppYt4rGLHlwMDhKXxdG7wOOfipCjvBtc%3D 
		
	});
	onShow(() => { });  
	// 去注册 
	const toRegister = async(activateTicket) =>{   
		let modalRegister = {
		  "activateTicket": activateTicket,
		  "openid": uni.getStorageSync("userInfo").openId,
		  "unionID":uni.getStorageSync("userInfo").unionID,
		  "promotionUser":uni.getStorageSync("promotionUser"),
		  "comSharingCardNo":uni.getStorageSync("comSharingCardNo") 
		}   
		// 注册 并 获取用户信息
		const dataRegister = await HFiveRegister(modalRegister) 
		try{
			if(!dataRegister.userInfo.token){
				uni.showToast({ title: '当前token不存在，请联系管理员!', icon: 'none' })
				return 
			}
		}catch(e){
			//TODO handle the exception
		} 
		uni.setStorageSync("token", dataRegister.userInfo.token)  
		uni.setStorageSync('userInfo',dataRegister.userInfo) 
		// 获取门店信息
		const shopInfo  = await GetBaseConfigInfoH5()
		let cardsModal = { "functionName":"MemberInfo_H5", "contentData": ""}
		// 获取卡列表信息
		const cardsInfo  = await HFiveMemberAppObjProcess(cardsModal) 
		const oneCardInfo = cardsInfo[0] // 默认第一张    
		uni.setStorageSync('shopInfo',shopInfo)
		uni.setStorageSync('cardInfo',oneCardInfo)   
		if(dataRegister.userInfo && shopInfo && cardsInfo){
			// uni.showToast({ title: '注册 ： 当前用户已开通会员直接登录注册 ： ', icon: 'none' })
			scanTodo() 
		}else{
			uni.showToast({ title: '已开卡注册，获取用户信息失败，请联系管理员', icon: 'none' }) 
		}  
	} 

    // 获取IOS地址配置jssdk
    const  getConfigUrl = ()=> {
        let u = window.navigator.userAgent;
        let isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
        if (isiOS) {
         let url =  window.location.href//获取初始化的url相关参数
    		uni.setStorageSync('IOS_URL',url) 
        } 
    }
	
    // const pathUrl = ref('https://jtmckj.cn/ch/') // 赤红 
	// const pathUrl = ref('https://jtmckj.com/tgx/') // 踏歌行
	// const pathUrl = ref('https://jtmckj.com/zttt/') //在桃兔兔
	// const pathUrl = ref('https://jtmckj.cn/qnjg/')  //青年酒馆
	
	const getWxUserInfoCode = () => { 
		let link = window.location.href;
		// console.log(link, 'link');

		let code = null;

		// let appid = 'wxd536727fd1a498a7'; // 正式
		let appid = setting.APP_ID;  // appid
		let uri =  setting.APP_PATH //跳转地址 
		// `https://jtmckj.cn/kbq/?brd=${brandCode}&org=${orgCode}`   
		// let uri = 'https://jtmckj.cn/kbq?like=' + '123555' + '&new=' + '96987'; //重定向地址 加上brandCode orgCode
		// let appsecret = "填写公众号开发者秘钥"; //公众号开发者秘钥  需要前端自行获取时才需要
		// 判断link中有没有code=字符串
		// if (link.indexOf('code=') === -1) {
		if (uni.getStorageSync('LoginFlag')) {
			// let uri2 = encodeURIComponent(uri)
			uni.showToast({ title: '获取信息中，请稍等', icon: 'none' }) 
			window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${uri}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`;
		} else {
			let temp = link.split("code=")[1];
			code = temp.split("&")[0];  
			getWxInFo(code) 
		}
	} 
	
	// 后端获取 通过code获取openId、token等微信基础信息
	const getWxInFo = async (code) => { 
		let codeModal = { "code": code,"promotionUser":uni.getStorageSync("promotionUser"),"comSharingCardNo":uni.getStorageSync("comSharingCardNo") }
		// 获取用户信息
		const userInfoData = await  HFiveLogin(codeModal)
		try{
			if(!userInfoData.userInfo.token){
				uni.showToast({ title: '当前token不存在，请联系管理员~', icon: 'none' })   
				return
			}
		}catch(e){
			//TODO handle the exception
		} 
		uni.setStorageSync("token", userInfoData.userInfo.token) 
		uni.setStorageSync("userInfo", userInfoData.userInfo) 
		console.log('userInfo:', userInfoData.userInfo)  
		// 判断是否开卡 loginstatus === 1 已开通会员直接登录 - 获取基础信息并存储各类信息
		if (userInfoData.loginstatus === 1) {  
			// uni.showToast({ title: '登录 - 当前用户已开通会员直接登录', icon: 'none' })   
			// 获取门店信息
			const shopInfo  = await GetBaseConfigInfoH5()  
			// 获卡列表信息
			let cardsModal = { "functionName":"MemberInfo_H5", "contentData": "" }
			const cardsInfo  = await HFiveMemberAppObjProcess(cardsModal) 
		    const oneCardInfo = cardsInfo[0]
			console.log('shopInfo：',shopInfo) 
			console.log('cardsInfo：',cardsInfo)  
			uni.setStorageSync('shopInfo',shopInfo)
			uni.setStorageSync('cardInfo',oneCardInfo) 
			scanTodo()
		} else {
			// 去第三方平台开卡 >>> 开卡成功需要跳转到 >>> 我的页面 -然后去注册开台会员信息-然后获取基础信息并存储各类信息
			uni.showToast({ title: '前往开卡中,请稍等~~~', icon: 'none' })   
			let modal2 = {
				"functionName": "CreadMemberCard", 
				"contentData": {Url:setting.APP_PATH}

			}
			uni.setStorageSync('NewMember',true)
			const datauUrl = await HFiveAppObjProcess(modal2)   
			setTimeout(()=>{
			  	window.location.href = datauUrl 
			},1500)
			
		}  
	} 

	const scanTodo = ()=>{
		uni.removeStorageSync('cartList')
		let scanInfo = uni.getStorageSync('scanInfo')  // 扫码信息
		let topath = uni.getStorageSync('toPath') || ''
		switch (topath) {
			case 'order': // 点单
			
			let shopInfo = uni.getStorageSync('shopInfo')
				// uni.reLaunch({
				// 	url: '/pagesOrder/view/goods/index'
				// })
				if(shopInfo && shopInfo.brandCode == '0005' && shopInfo.orgCode == '0018'){ // 空白区扫码开台
					RoomOpenFun()
				}
				
				console.log(uni.getStorageSync('tableInfo'));
				
				if(shopInfo && shopInfo.isAddFriend){
				    HFiveMemberAppObjProcess({ functionName: "IsAddWork_H5", contentData: "" }).then(res => {
				        uni.reLaunch({
				        	url: '/pages/home/index'
				        })
				        uni.setStorageSync('showAdv',true)
				    }).catch(err => {
				        uni.reLaunch({
				        	url: '/subpkg/view/promoteCode/promoteCode'
				        })
				    })
				}else{
				    uni.reLaunch({
				    	url: '/pages/home/index'
				    })
				    uni.setStorageSync('showAdv',true)
				}
				
				// uni.reLaunch({
				// 	url: '/pages/home/index'
				// })
				// uni.setStorageSync('showAdv',true)
				break;
			case 'queue': // 排队
				uni.reLaunch({
					url: '/subpkg/view/lineupMember/lineupMember'
				})
				break;
			case 'QueueQuery': // 排队查询
				uni.reLaunch({
					url: '/subpkg/view/queueRecord/queueRecord'
				})
				break;
			case 'queueQuery': // 排队查询
				uni.reLaunch({
					url: '/subpkg/view/queueRecord/queueRecord'
				})
				break;
			case 'memRecharge': // 储值
				if(scanInfo && scanInfo.IsScanRecharge){
					uni.reLaunch({
					  url: '/subpkg/view/centerStore/centerStore?IsScanRecharge=true'
					})
				}else{
					uni.reLaunch({
						url: '/subpkg/view/centerStore/centerStore'
					})
				}
				
				break;
			case 'pointShop': // 积分商城
				if(scanInfo && scanInfo.typeSpe){
					uni.reLaunch({
						url: '/pagesPointShop/view/index?typeSpe=1'
					})
				}else{
					uni.reLaunch({
						url: '/pagesPointShop/view/index'
					})
				}
				
				if(scanInfo && scanInfo.userCode){
					uni.setStorageSync('pointInviter',scanInfo.userCode)
				}
				break;
			case 'scanSend': //  扫码赠送
				uni.reLaunch({
					url: '/subpkg/view/scanSend/scanSend'
				})
				break;
			case 'goodsPreview': //  商品预览
				uni.reLaunch({
					url: '/pagesOrder/view/goods/preview'
				})
				break;
			case 'gift': //  打赏
				uni.reLaunch({
					url: '/subpkg/view/gift/gift'
				})
				break;
			default:
				uni.reLaunch({
					url: '/pages/home/index'
				})
				uni.setStorageSync('showAdv',true)
				break;
		}
		uni.removeStorageSync('toPath') // 跳转后删除
		
		let tableCode = uni.getStorageSync('tableInfo')?.code // 桌台信息
		if(tableCode){ // 扫码后跟新房台
			updateTableInfo(tableCode)
		}
		
		
	}
	
	// 扫码开台
	const RoomOpenFun = (typeName) => {
		const userInfo = uni.getStorageSync('userInfo')
		const tableInfo = uni.getStorageSync('tableInfo') // 桌台信息
		let modal = {
			"functionName": "MemberRoomOpen_H5",
			"contentData": {
				"memberName": userInfo.name,
				"memberMobile": userInfo.mobile,
				"memberOpenid": userInfo.openId,
				"sex": userInfo.sex,
				"roomCode": tableInfo.code
			}
		}
		HFiveMemberAppObjProcess(modal)
	}
	
	
	
	// 前端通过微信api自行获取openid
	// const getWxInFoByQD = () => {
	// 	console.log('getWxInFoByQD...')
	// 	uni.request({
	// 		url: "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appid + "&secret=" + appsecret + "&code=" + code + "&grant_type=authorization_code",
	// 		method: "GET",
	// 		success: function(res) {
	// 			console.log(res)
	// 			if (res.statusCode === 200) {
	// 				//以获取的openid
	// 				console.log(res.data.openid)
	// 				this.$api.msg('用户信息openid' + res.data.openid);
	// 			}
	// 		},
	// 		fail: function(err) {
	// 			console.log(err)
	// 		}
	// 	})
	// } 
	
</script>

<style scoped lang="less">

</style>